import { useEffect, useState } from 'react'

// import { getRouteReallyPath } from '@/utils/routesTree'
import { formatDateTime } from '@/utils/displayHelper'
import { cx } from '@/utils/stringUtil'

const lastUpdateCache = { code: -1, watcher: [], data: undefined }

const loopCallThenPop = async (list = [], then = it => it) => {
  const op = list.pop()
  const res = then(op)
  if (res && res.then) {
    await res
  }
  if (list.length) {
    await loopCallThenPop(list, then)
  }
}

const getConfigData = () =>
  new Promise(resolve => {
    if (lastUpdateCache.data) {
      return resolve(lastUpdateCache.data)
    }
    if (lastUpdateCache.code === -1) {
      lastUpdateCache.data = 206
      lastUpdateCache.watcher.push(resolve)
      window
        .appDispatch({ type: 'app/selectStore', payload: { keys: ['userEntrancesList', 'currentEntranceId'] } })
        .then(({ userEntrancesList, currentEntranceId }) => {
          lastUpdateCache.data = { userEntrancesList, currentEntranceId }
          loopCallThenPop(lastUpdateCache.watcher, rl => rl(lastUpdateCache.data))
        })
    } else {
      lastUpdateCache.watcher.push(resolve)
    }
  })

const detailConfig = {
  XCPBS: {
    typeDesc: '现场评标室',
    detailDesc: '评标确认详情',
    pageKey: 'evaluationRoomDetail', // 走路由跳转的配置这里
    widget: undefined, // 走模块弹窗的配置这里
  },
  // eslint-disable-next-line camelcase
  tendering_confirmation_detail: {
    typeDesc: '现场评标室',
    detailDesc: '评标确认详情',
    pageKey: 'evaluationRoomDetail', // 走路由跳转的配置这里
    widget: undefined, // 走模块弹窗的配置这里
  },
  YSGD: {
    typeDesc: '工单管理',
    detailDesc: '工单详情',
    // widget: () => import('@/pages/workOrderManage/components/detailDrawer'), // 走模块弹窗的配置这里
  },
}

const onClickMessage = async (message, afterView) => {
  afterView && afterView(message)
  const {
    businessType,
    title = '--',
    noticeId,
    businessId,
    content = '--',
    createTime,
    idAlias,
    displayForm, // 1 红点， 2 弹窗 3 横幅
    moduleId,
  } = message
  const messageTargetConfig = detailConfig[message.businessType]
  const { userEntrancesList, currentEntranceId } = await window.appDispatch({
    type: 'app/selectStore',
    payload: { keys: ['userEntrancesList', 'currentEntranceId'] },
  })
  const targetModule = userEntrancesList.find(it => it.moduleId === message.moduleId)
  if (targetModule && currentEntranceId !== targetModule.entranceId) {
    const res = await window.appDispatch({ type: 'app/getMenuList', payload: { entranceId: targetModule.entranceId } })
    if (res === false) {
      return
    }
  }
  if (messageTargetConfig.pageKey) {
    // gotoDvaHashUrl({
    //   url: getRouteReallyPath(messageTargetConfig.pageKey, { ...message, noticeId, [idAlias]: businessId, businessId }),
    // })
  } else if (messageTargetConfig.widget) {
    let Tag = messageTargetConfig.widget
    if (messageTargetConfig.widget instanceof Function) {
      let res = messageTargetConfig.widget()
      if (res && res.then) {
        res = await res
      }
      Tag = (res && res.default) || res
      if (!Tag) {
        return
      }
    }
    return Tag.PromiseThen({
      ...message,
      noticeId,
      [idAlias]: businessId,
      businessId,
      orderId: businessId,
    })
  }
}

let userEntrancesList

/**
 * 消息条目及跳转
 * @param message
 * @param afterView
 * @returns {JSX.Element}
 * @constructor
 */
const MessageJump = ({ message = {}, afterView, context }) => {
  const [userEntrancesList, setUserEntrancesList] = useState([])
  const [currentEntranceId, setCurrentEntranceId] = useState()
  if (message.businessType === 1) {
    message.businessType = 'tendering_confirmation_detail'
  }
  const { businessType, title = '--', noticeId, businessId, content = '--', createTime, idAlias, displayForm } = message
  const messageTargetConfig = detailConfig[businessType]

  useEffect(() => {
    if (lastUpdateCache.data) {
      const { userEntrancesList, currentEntranceId } = lastUpdateCache.data
      setUserEntrancesList(userEntrancesList)
      setCurrentEntranceId(currentEntranceId)
    } else {
      getConfigData().then(data => {
        const { userEntrancesList, currentEntranceId } = data
        setUserEntrancesList(userEntrancesList)
        setCurrentEntranceId(currentEntranceId)
      })
    }
  }, [])

  if (!messageTargetConfig) {
    return null
  }

  return (
    <div
      key={noticeId}
      style={{
        borderBottom: [undefined, 1].includes(displayForm) ? '1px solid #ededed' : undefined,
        cursor: 'pointer',
        padding: '10px',
        alignItems: 'baseline',
      }}
      className='ui-flex ui-flex-between'
      onClick={() => onClickMessage(message, afterView)}
    >
      <div className='ui-action mr20px' style={{ whiteSpace: 'nowrap' }}>
        {message.title || messageTargetConfig.typeDesc}
      </div>
      <div style={{ width: '100%', flexGrow: 1 }}>
        <div className={cx([undefined, 1].includes(displayForm) && 'mb5px f-twoLine')} style={{ overflow: 'hidden' }}>
          {(content || '')
            .replace(/(\r|\n){2,}/g, '\n')
            .split('\n')
            .join('，')}
        </div>
        {[undefined, 1].includes(displayForm) && <p className='ui-color ui-color-gray'>{formatDateTime(createTime)}</p>}
      </div>
      <div className='ml20px ui-action' style={{ whiteSpace: 'nowrap' }}>
        查看
      </div>
    </div>
  )
}

MessageJump.getResolvedData = message => {
  const {
    businessType,
    title = '--',
    noticeId,
    businessId,
    content = '--',
    createTime,
    idAlias,
    displayForm, // 1 红点， 2 弹窗 3 横幅
    moduleId,
  } = message
  const messageTargetConfig = detailConfig[businessType]
  return {
    typeDesc: message.title || messageTargetConfig.typeDesc,
    content: (content || '')
      .replace(/(\r|\n){2,}/g, '\n')
      .split('\n')
      .join('，'),
    onClickMessage,
  }
}

export default MessageJump
